package cn.wolfcode.mq;

import cn.wolfcode.ws.WebSocketServer;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "MQOrderResultConsumer",
        topic = MQConstant.ORDER_RESULT_TOPIC
)
public class MQOrderResultConsumer implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //通过下单逻辑拿到消息中的token
        String token = orderMQResult.getToken();
        //通过消息中的token，拿到对应的客户端信息
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        try {
            if (webSocketServer != null) {
                webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
            }
            //最后再通过下单成功的逻辑把订单编号返回给递推给客户端
            /*String orderNo = orderMQResult.getOrderNo();

            if (orderNo==null){
            }
            webSocketServer.getSession().getBasicRemote().sendText(orderNo);*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
